package com.yotoodesign.dianba.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.yotoodesign.core.util.NetUtil;
import com.yotoodesign.core.util.ZipUtil;
import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.bean.Version;

public class DownloadUtil {
	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;

	private ProgressBar mProgress;
	private int progress = 0;

	private String fileDownUrl = "http://www.yotoodesign.com/download/dianba.rar";// 文件下载地址
	public static String saveFileName = "dianba.zip";//文件名称
	public static String savePath = "com.yotoodesign.maiba";//文件保存路径

	private String versionUrl = "http://www.yotoodesign.com/download/version.xml";// 文件下载地址
	public static String versionXml = "version.xml";//应用文件名称

	private String apkUrl = "http://www.yotoodesign.com/download/dianba.apk";// 文件下载地址
	public static String apkName = "dianba.apk";//应用文件名称
	
	private Context mContext;

	private boolean interceptFlag;//暂停下载标志
	private AlertDialog downloadDialog;//下载对话框

	private Thread downLoadThread;
	
	private String SDPATH;
	
	private String state;
	private boolean hasSdCard = false;
	
	private int funcode = 10001;//10001:同步数据,10002:版本检查,10003:新版本下载
	
	public static String currentVer = "1.0.0";//当前版本

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER://下载完成后，读取文件内容
				//关闭窗口
				downloadDialog.dismiss();
				
				switch(funcode){
				case 10001://同步数据
					Toast.makeText(mContext, "同步数据完成!", Toast.LENGTH_SHORT).show();
					String unZipfile = SDPATH + savePath + "/" + saveFileName;
					ZipUtil zip = new ZipUtil();
					
					String destPath = SDPATH + savePath;
					File destFile = new File(destPath);
					//如果用户指定的解压目录不存在，则先创建
					if(!destFile.exists())
					{
						destFile.mkdirs();
					}
					zip.unZip(unZipfile, destPath);
					Toast.makeText(mContext, "处理数据结束!", Toast.LENGTH_SHORT).show();
					break;
				case 10002://版本检查
					String verxml = SDPATH + savePath + "/" + saveFileName;
					Version version = VersionService.getInstance().prepare(verxml);
					if(!currentVer.equals(version.getVer())){
						AlertDialog.Builder builder = new Builder(mContext);
						builder.setTitle("提示").setMessage("检查到新版本 "+version.getVer()+"："+version.getDesc()+"，现在要下载吗？")
							.setIcon(R.drawable.logo)
							.setPositiveButton("确认", new OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog, int which) {
									new DownloadUtil(mContext).showDownloadDialog("新版本下载中...",10003);
								}
							}).setNegativeButton("取消", new OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
								
							})
							.create().show();
					}else{
						Toast.makeText(mContext, "当前已是最新版本！", Toast.LENGTH_SHORT).show();
					}
					break;
				case 10003://新版本下载完成
					//自动安装
					setupApk();
					break;
				}
				
				break;
			default:
				break;
			}
		};
	};

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				if(new NetUtil(mContext).isConnected()==false){
					Looper.prepare();
					downloadDialog.dismiss();
					Toast.makeText(mContext, "网络似乎不通哦!", Toast.LENGTH_SHORT).show();
					Looper.loop();
					return;
				}
				URL url = new URL(fileDownUrl);

				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();
				
				File dbFile = null;
				if(hasSdCard){
					// 创建目录
					createSDDir(savePath);
					// 创建文件
					dbFile  = createSDFile(savePath + "/"+ saveFileName);
					
				}else{//如果没有SD卡，就保存在应用目录内
					dbFile = new File(mContext.getFilesDir().getAbsolutePath() +"/"+ saveFileName);
					dbFile.createNewFile();
				}

				FileOutputStream fos = new FileOutputStream(dbFile);
				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知结束
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				Looper.prepare();
				downloadDialog.dismiss();
				Toast.makeText(mContext, "没找到数据文件，请与作者联系！", Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		}
	};

	//启动文件下载线程
	private void downloadFile(int funcode) {
		this.funcode = funcode;
		switch(funcode){
		case 10002:
			this.fileDownUrl = this.versionUrl;
			DownloadUtil.saveFileName = DownloadUtil.versionXml;
			break;
		case 10003:
			this.fileDownUrl = this.apkUrl;
			DownloadUtil.saveFileName = DownloadUtil.apkName;
			break;
		}
		
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}
	
	public DownloadUtil(Context context){
		this.mContext = context;
		
		state = Environment.getExternalStorageState();
		if(state.equals(Environment.MEDIA_MOUNTED)){
			hasSdCard = true;
			// 得到当前SD卡目录
			SDPATH = Environment.getExternalStorageDirectory() + "/";
		}
	}
	
	// 文件下载入口
	public void showDownloadDialog(String title,int funcode) {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(title);
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.update_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);

		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		
		downloadDialog = builder.create();
		downloadDialog.show();
		downloadFile(funcode);
	}
	
	/**
	 * 在SD卡上创建目录
	 * 
	 * @param dirName
	 * @return
	 */

	public File createSDDir(String dirName) {
		File dir = new File(SDPATH + dirName);
		dir.mkdir();
		return dir;
	}
	
	/**
	 * 在SD卡上创建文件
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 */

	public File createSDFile(String fileName) throws IOException {
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}

	/*
	 * 读取文件内容，并放到列表里
	 */
	public  List<String> readTxtFile(String strFilePath)
    {
		List<String> result = new ArrayList<String>();
        String path = strFilePath;
            //打开文件
            File file = new File(path);
            //如果path是传递过来的参数，可以做一个非目录的判断
            if (file.isDirectory())
            {
                Log.d(Constant.DIANBA, "The File doesn't not exist.");
            }
            else
            {
                try {
                    InputStream instream = new FileInputStream(file); 
                    if (instream != null) 
                    {
                        InputStreamReader inputreader = new InputStreamReader(instream);
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line;
                        //分行读取
                        while (( line = buffreader.readLine()) != null) {
                            result.add(line);
                        }                
                        instream.close();
                    }
                }
                catch (java.io.FileNotFoundException e) 
                {
                    Log.d(Constant.DIANBA, "The File doesn't not exist.");
                } 
                catch (IOException e) 
                {
                     Log.d(Constant.DIANBA, e.getMessage());
                }
            }
            return result;
    }
	
	//安装APK
	private void setupApk() {
		File mFile = new File(SDPATH + savePath + "/" + saveFileName);
		
		// 系统定义的文件夹，需要在下载时候设置这个文件夹
		if (mFile.exists()) {
			Intent install = new Intent();
			install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			install.setAction(android.content.Intent.ACTION_VIEW);
			install.setDataAndType(Uri.fromFile(mFile),
					"application/vnd.android.package-archive");
			mContext.startActivity(install);
		}
	}

	public String getSaveFileName() {
		return saveFileName;
	}

	public void setSaveFileName(String saveFileName) {
		this.saveFileName = saveFileName;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

}
